package com.fuyun.rpc.registry.impl;

import cn.hutool.core.util.StrUtil;
import com.fuyun.rpc.constant.RpcConstant;
import com.fuyun.rpc.dto.RpcReq;
import com.fuyun.rpc.factory.SingletonFactory;
import com.fuyun.rpc.loadbalance.LoadBalance;
import com.fuyun.rpc.loadbalance.impl.RandomLoadBalance;
import com.fuyun.rpc.registry.ServiceDiscovery;
import com.fuyun.rpc.registry.zk.ZkCLient;
import com.fuyun.rpc.util.IpUtils;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @Author fuyun。
 * @Date 2025/8/22 11:50。
 * @Description: TODO。
 **/

public class ZkServiceDiscovery implements ServiceDiscovery {

    private final ZkCLient client;
    private final LoadBalance loadBalance;

    public ZkServiceDiscovery() {
        this(SingletonFactory.getInstance(ZkCLient.class), SingletonFactory.getInstance(RandomLoadBalance.class));
    }

    public ZkServiceDiscovery(ZkCLient client, LoadBalance loadBalance) {

        this.client = client;
        this.loadBalance = loadBalance;
    }

    @Override
    public InetSocketAddress lookupService(RpcReq rpcReq) {
        String path = RpcConstant.ZK_RPC_ROOT_PATH + StrUtil.SLASH + rpcReq.rpcServerName();
        List<String> children = client.getChildrenNode(path);
        String address = loadBalance.select(children);
        return IpUtils.toInetSocketAddress(address);
    }
}
